home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 11766 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: cypher.3do.com!user
  2. From: tsw@3do.com (Tom Watson)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: String Problem
  5. Date: Mon, 25 Mar 1996 17:21:13 -0800
  6. Organization: The 3DO Corporation
  7. Distribution: world
  8. Message-ID: <tsw-2503961721130001@cypher.3do.com>
  9. References: <4j6l61$4no@B1FF.mindspring.com>
  10. NNTP-Posting-Host: cypher.3do.com
  11.  
  12. In article <4j6l61$4no@B1FF.mindspring.com>, vtipres@atl.mindspring.com wrote:
  13.  
  14. > This is supposed to be a variation on sample code from a textbook.
  15. > Can anyone tell me why NameCheck = 0 when I run the program?
  16. > /*
  17. >    Testing character transactions.
  18. > */
  19. > #include <stdio.h>
  20. > #include <ctype.h>
  21. > int main()
  22. > {
  23. >    char Name[11] = "John";
  24.  
  25. You have initialized a local variable to the text "John" (with a trailing
  26. 'nul' character.  After that (the first 5 locations in the array) the data
  27. is undefined.
  28.  
  29. >    char *WhereName;
  30. >    int NameCheck = 0;
  31. >    WhereName = Name;
  32. >    if ( WhereName == "John" )
  33.  
  34. Here you are comparing a character pointer with the address of a constant
  35. (could be in read-only storage).  This is a completely different "John"
  36. from the first.  In ANSI C this cannot be changed, whereas the first one
  37. (declared in the 'Name' array) can be altered to your hearts content.
  38.  
  39. >    {
  40. >       NameCheck = 1;
  41. >    }
  42. >    printf( "Name: %s\n", Name );
  43. >    printf( "NameCheck = %i\n", NameCheck );
  44. >    printf( "WhereName = %i\n", WhereName );
  45.  
  46. The variable 'WhereName' is a pointer, and should not be printed with a
  47. '%i' formatting specification.  Pointers can be different sizes than ints
  48. (I use a compiler that this is the case!).  It should be printed with a
  49. '%p' specification if you want to see what it is.
  50.  
  51.  
  52. > }
  53.  
  54.  
  55. The basic problem is that your 'if' statement looks as if you want to
  56. compare the two strings ans see if they are equal.  This cannot be done in
  57. the base language wiothout using the library.  If you really want to
  58. compare the strings, the proper call might look like:
  59.  
  60.        if (strcmp (WhereName, "John") == 0)
  61.  
  62. In any event, a good looking at the FAQ's might answer some of these
  63. things.  Even if it doesn't, it contains quite a bit of VERY good clues on
  64. lots of topics.
  65.  
  66. p.s.  What textbook??
  67.  
  68. -- 
  69. Tom Watson
  70. tsw@3do.com         (Home: tsw@johana.com)
  71.